###############################################################################
#                                                                             #
#    This file is part of the testsuite of the "ssbot" Python module.         #
#    It is distributed under the MIT License. See LICENSE.txt for details.    #
#                                                                             #
###############################################################################


import os
import os.path
import sys
import time
import unittest

sys.path.append('../')

import ssbot.steps


class StepTimeoutTests(unittest.TestCase):
    def setUp(self):
        self.start_text = 'started'
        self.complete_text = 'completed'
        self.script = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'helpers', 'step_timeout_tests_helper.py')
        self.timeout_status_file = '.__ssbot_step_timeout_test_status_file'
        with open(self.timeout_status_file, 'w') as f:
            f.write(self.start_text)

    def tearDown(self):
        if os.path.exists(self.timeout_status_file):
            os.remove(self.timeout_status_file)

    def test_step_timing_out(self):
        step = ssbot.steps.Step(
            'test_step',
            [self.script, '30', self.timeout_status_file, self.complete_text],
            cwd=os.path.abspath('.'),
            timeout=5)
        result = step.run(base_path=os.path.abspath('.'))
        self.assertEqual(result['stdout'], 'Timed out')
        self.assertEqual(result['stderr'], 'Timed out')
        with open(self.timeout_status_file, 'r') as f:
            text = f.read()
            self.assertEqual(self.start_text, text)
        time.sleep(40)
        with open(self.timeout_status_file, 'r') as f:
            text = f.read()
            self.assertEqual(self.start_text, text)

    def test_step_finishing_within_timeout(self):
        step = ssbot.steps.Step(
            'test_step',
            [self.script, '5', self.timeout_status_file, self.complete_text],
            cwd=os.path.abspath('.'),
            timeout=7)
        result = step.run(base_path=os.path.abspath('.'))
        with open(self.timeout_status_file, 'r') as f:
            text = f.read()
            self.assertEqual(self.complete_text, text)

    def test_step_without_timeout(self):
        step = ssbot.steps.Step(
            'test_step',
            [self.script, '2', self.timeout_status_file, self.complete_text],
            cwd=os.path.abspath('.'))
        result = step.run(base_path=os.path.abspath('.'))
        with open(self.timeout_status_file, 'r') as f:
            text = f.read()
            self.assertEqual(self.complete_text, text)


if __name__ == '__main__':
    unittest.main()
